package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.StrategyCatalog;
import cn.wolfcode.luowowo.query.StrategyCatalogQuery;
import cn.wolfcode.luowowo.repository.StrategyCatalogRepository;
import cn.wolfcode.luowowo.repository.StrategyRepository;
import cn.wolfcode.luowowo.service.IStrategyCatalogService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.vo.CatalogVO;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.mongo.MongoClientDependsOnBeanFactoryPostProcessor;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {


    @Autowired
    private StrategyCatalogRepository strategyCatalogRepository;

    @Autowired
    private IStrategyService strategyService;


    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(StrategyCatalog strategyCatalog) {
        strategyCatalog.setId(null);
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {

        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        strategyCatalogRepository.deleteById(id);

    }

    @Override
    public StrategyCatalog get(String id) {
        Optional<StrategyCatalog> op = strategyCatalogRepository.findById(id);
        if (op.isPresent()){
            StrategyCatalog strategyCatalog = op.get();
            return strategyCatalog;
        }
        return null;
    }

    @Override
    public List<StrategyCatalog> list()
    {
        return strategyCatalogRepository.findAll();
    }

    // 分页操作
    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQuery qo) {

        Query query = new Query();
        // 查询总页数
        long count = mongoTemplate.count(query, StrategyCatalog.class);
        if (count == 0){
            return Page.empty();
        }

        // 分页排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        query.with(pageable);

        List<StrategyCatalog> list = mongoTemplate.find(query, StrategyCatalog.class);


        return new PageImpl<>(list,pageable,count);

    }

    /**
     * 攻略明细分类下拉框回显
     * @return
     */
    public List<CatalogVO> groupList() {
        List<CatalogVO> list = new ArrayList<>();
        // MongoDB 聚合方法
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        push("name").as("names").
                        push("id").as("ids")
        );
        AggregationResults<Map> result = mongoTemplate.aggregate(agg,Map.class);
        // 拿到List 集合
        List<Map> datas = result.getMappedResults();
        // 遍历List 拿到每个Map
        for (Map data : datas) {
            // new  一个 Vo 类
            CatalogVO vo = new CatalogVO();
            // data中的_id就是DestName;拿到每一个set 进 Vo的destName属性只能够
            vo.setDestName(data.get("_id").toString());

            //  在new  一个List
            List<Map<String, Object>> mm = new ArrayList<>();
            // data中每个攻略分类的Ids  和  names  都是个集合
            List<Object> names = (List<Object>) data.get("names");
            List<Object> ids = (List<Object>) data.get("ids");
            // 遍历集合
            for (int i = 0;i < names.size(); i++) {
                // new  一个 Map
                Map<String, Object> vv = new HashMap<>();
                // 拿到相同索引的name 和 list  一起存到一个Map中
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                vv.put("id", id);
                vv.put("name", name);
                // 然后每遍历一次就把这个Map装进list中
                mm.add(vv);
            }
            //  在把Map装进Vo的 MapList属性 中
            vo.setMapList(mm);
            // 最后把每个对象转进List中
            list.add(vo);
        }
        System.out.println(list);
        return list;
    }

    /**
     * // 目的地下分类概况/明细
     * @param destId
     * @return
     */
    @Override
    public List<StrategyCatalog> queryCatalogsByDestId(String destId) {

        //  根据传上来的目的地Id  找到 攻略分类集合
      List<StrategyCatalog> catalogs  = strategyCatalogRepository.findByDestId(destId);

        // 遍历攻略分类集合
        for (StrategyCatalog catalog : catalogs) {

            // 通过每个攻略分类对象的Id作为条件 找到攻略明细集合
            List<Strategy> strategies = strategyService.queryCatalogsByCatalogId(catalog.getId());
            // set攻略分类对象的Strategies 属性中
            catalog.setStrategies(strategies);
        }


        return catalogs;
    }


}
